<?php
class RCMSMenu {
	protected $defs = array();
	protected $menus = null;
	protected $parent = null;

	public function __construct($defs) {
		$this->defs = array_merge(array(
			'MENU_ID'   => '',
			'MENU_PARENT_ID'   => '',
			'MENU_TYPE' => '',
			'MENU_GROUP_NAME' => '',
			'MENU_NAME'    => '',
			'MENU_TITLE'   => '',
		), $defs);
	}
	public function getDefinitions() {
		return $this->defs;
	}
	public function getDeep() {
		return $this->defs['PARSED_DEEP'];
	}
	public function getTitle() {
		return $this->defs['MENU_TITLE'];
	}
	public function getUrl() {
		return $this->defs['PARSED_PATH'];
	}
	protected function getParentMenu($menus, $cmenu) {
		$cdefs = $cmenu->getDefinitions();
		if ($cdefs['MENU_PARENT_ID'] == -1) {
			return null;
		}
		foreach ($menus as $menu) {
			$defs = $menu->getDefinitions();
			if (($defs['SYSTEM_ID'] === $cdefs['SYSTEM_ID']) &&	($defs['SUBSYS_ID'] === $cdefs['SUBSYS_ID']) &&
			($defs['SYSTEM_LANG'] === $cdefs['SYSTEM_LANG']) && ($defs['MENU_ID'] === $cdefs['MENU_PARENT_ID'])) {
				return $menu;
			}
		}
		throw new RuntimeException('not found parent menu:'.print_r($cdefs));
	}
	public function setParent($parentMenu) {
		$this->parent = $parentMenu;
	}
	public function compile($menus) {
		$this->menus = $menus;
		$parentMenu = $this->getParentMenu($menus, $this);
		$this->setParent($parentMenu);
		if (is_null($parentMenu)){
			$this->defs['PARSED_DEEP'] = 0;
			$this->defs['PARSED_PATH'] = '/';
		} else {
			$defs = $parentMenu->getDefinitions();
			$this->defs['PARSED_DEEP'] = $defs['PARSED_DEEP'] + 1;
			if ($defs['PARSED_PATH'] == '/') {
				$this->defs['PARSED_PATH'] = '/'.$this->defs['MENU_NAME'];
			} else {
				$this->defs['PARSED_PATH'] = $defs['PARSED_PATH'].'/'.$this->defs['MENU_NAME'];				
			}
		}
	}
}
